using System;
using Microsoft.SharePoint;
using System.Collections.Generic;
using Microsoft.SharePoint.Administration;
using System.Globalization;
using Microsoft.SharePoint.Utilities;

namespace Evolution.EventReceivers
{
    [System.ComponentModel.Category("86439C8D-36E3-46e6-B801-D35B1D01B4C0")] //Don't remove! This attribute is added by SPVisualDev to bind it to a WSS feature ID.
    public class WebPartsFeatureEventReceiver : SPFeatureReceiver
    {
        public WebPartsFeatureEventReceiver()
        {
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb rootWeb = (properties.Feature.Parent as SPSite).RootWeb;
            SPDocumentLibrary gallery = (SPDocumentLibrary)rootWeb.Lists["Web Part Gallery"];

            Dictionary<string, int> webparts = new Dictionary<string, int>();
            foreach (SPListItem item in gallery.Items)
                webparts.Add(item["Title"].ToString(), item.ID);

            CultureInfo culture = CultureInfo.InvariantCulture;
            SPElementDefinitionCollection elements = properties.Definition.GetElementDefinitions(culture);

            foreach (SPElementDefinition element in elements)
            {
                if (element.ElementType == "Module")
                {
                    string resource = properties.Feature.Definition.DefaultResourceFile;
                    string name = SPUtility.GetLocalizedString(element.XmlDefinition.Attributes["Name"].Value, resource, Convert.ToUInt32(culture.LCID));
                    if (webparts.ContainsKey(name))
                    {
                        SPListItem item1 = gallery.GetItemById(webparts[name]);
                        item1.Delete();
                    }

                }
            }
            gallery.Update();
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
    }
}
